package work.jame.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import work.jame.blog.pojo.UserArticleHistory;
import work.jame.blog.mapper.UserArticleHistoryMapper;
import work.jame.blog.service.UserArticleHistoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Jame
 * @since 2023-05-18
 */
@Service
public class UserArticleHistoryServiceImpl extends ServiceImpl<UserArticleHistoryMapper, UserArticleHistory> implements UserArticleHistoryService {


    @Override
    public Long queryArticleViewNumber(Long articleId) {
        QueryWrapper<UserArticleHistory> wrapper = new QueryWrapper<>();
        wrapper.eq("article_id", articleId)
                .groupBy("user_id");
        return this.count(wrapper);
    }

    @Override
    public UserArticleHistory queryUserWatchedArticle(Long userId, Long articleId) {
        QueryWrapper<UserArticleHistory> wrapper = new QueryWrapper<>();
        wrapper.eq("article_id", articleId)
                .eq("user_id", userId);
        return this.getOne(wrapper);
    }

    @Override
    public boolean saveOrUpdateUserArticleHistory(Long userId, Long articleId) {
        UserArticleHistory dbHistory = this.queryUserWatchedArticle(userId, articleId);
        if (Objects.isNull(dbHistory)) {
            UserArticleHistory history = new UserArticleHistory();
            history.setUserId(userId);
            history.setArticleId(articleId);
            history.setWatchNumber(1);
            return this.save(history);
        }
        dbHistory.setWatchNumber(dbHistory.getWatchNumber() + 1);
        return this.updateById(dbHistory);
    }
}
